package com.sl.biz.modular.ai.service.impl;

import cn.hutool.core.date.DateUtil;
import com.google.common.collect.Lists;
import com.sl.auth.core.util.StpCompositeUtil;
import com.sl.biz.modular.ai.dao.domain.entity.AiChatHistoryDO;
import com.sl.biz.modular.ai.dao.service.AiChatHistoryDaoService;
import com.sl.biz.modular.ai.service.AiChatHistoryBizService;
import com.sl.common.page.CommonPageRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

@Service
@RequiredArgsConstructor
public class AiChatHistoryBizServiceImpl implements AiChatHistoryBizService {

    private final AiChatHistoryDaoService aiChatHistoryDaoService;

    @Override
    public Boolean save(AiChatHistoryDO aiChatHistoryDO) {
        return batchSave(Lists.newArrayList(aiChatHistoryDO));
    }

    @Override
    public Boolean batchSave(List<AiChatHistoryDO> chatHistoryList) {
        for (AiChatHistoryDO aiChatHistoryDO : chatHistoryList) {
            aiChatHistoryDO.setUserId(StpCompositeUtil.getUserId());
            aiChatHistoryDO.setStartTime(DateUtil.date());
        }

        return aiChatHistoryDaoService.saveBatch(chatHistoryList);
    }

    @Override
    public List<AiChatHistoryDO> getByAiChatId(AiChatHistoryDO aiChatHistoryDO) {
        CommonPageRequest.setPageIs(true);
        CommonPageRequest.setPageSize(100L);
        CommonPageRequest.setCurrent(1L);
        List<AiChatHistoryDO> aiChatHistoryDOS = aiChatHistoryDaoService.pageByAiChatId(aiChatHistoryDO.getAiChatId(), StpCompositeUtil.getUserId());
        aiChatHistoryDOS = aiChatHistoryDOS.stream().sorted(Comparator.comparing(AiChatHistoryDO::getStartTime)).toList();
        return aiChatHistoryDOS;
    }

    @Override
    public Boolean clearHistory(AiChatHistoryDO aiChatHistoryDO) {
        return aiChatHistoryDaoService.removeByAiChatId(aiChatHistoryDO.getAiChatId());
    }
}
